package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import cn.com.kh.batch.BatchDeal_Utils
import cn.com.kh.result.iAPIResult
import com.wisdge.web.IPUtils
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/* GetCustomerInfo2 是GetCustomerInfo的替代版本 */

public class GetCustomerInfo implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(GetCustomerInfo.class);

    String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();
        JSONObject res_Json = iAPIResult.ERROR("获取-个人用户信息查询 失败");

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            res_Json = iAPIResult.ERROR("API被非法IP调用-Request Not Allow!" + IPUtils.getRemoteIP(request));
            log.warn(res_Json);
            return res_Json;
        }

        String getMethod = request.getMethod();
        log.debug("HTTP请求调用类型 getMethod:" + getMethod);
        if (getMethod != "POST" && getMethod != "GET") {
            res_Json = iAPIResult.ERROR("HTTP请求调用类型错误，接口调用失败：" + getMethod);
            log.error(res_Json);
            return res_Json;
        }

        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("Call Header-" + key + ":" + value);

            mapHeader.put(key, value);
        }

        // 获取所有参数名
        Map<String, String> mapParam = new HashMap<String, String>();
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String key = (String) ep.nextElement();
            String value = request.getParameter(key);
            log.debug("Call Parameter-" + key + ":" + value);
            mapParam.put(key, value);

        }

        // 获取数据源List<Map<String, Object>>
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 获取调用数据
        String callPram = "";
        if (getMethod.equals("GET")) {
            callPram = request.getQueryString();
            log.info("接收调用GET参数信息：" + callPram);
        } else if (getMethod.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                callPram += line;
            }
            log.info("接收调用POST报文信息：" + System.getProperty("line.separator") + callPram);
        }

        try {
            // 解析请求报文
            String rec_Guid = KHUtil.getRandomString(36);
            String customerId = KHUtil.GetMapV(mapParam, "customeroid");

            // 列表接口调用
            if (KHUtil.isNull(customerId)) {
                res_Json = iAPIResult.ERROR("请求参数customeroid不能为空，接口调用失败");

            } else {
                JSONObject res_RegJson = BatchDeal_Utils.custRegister(jt, rec_Guid, customerId, "");
                log.debug("-循环检查处理导入的客户编号(注册->认证) Cc_CustomerId:" + customerId + " res_RegJson:" + res_RegJson.toString());

                String res_Code = KHUtil.GetSFJV(res_RegJson, "code");
                String res_Msg = KHUtil.GetSFJV(res_RegJson, "msg");

                // res_Code=0 等待认证 res_Code=1检查通过(已注册&已认证) res_Code=-1->异常
                if (res_Code.equals("1") || res_Code.equals("0")) {
                    String checkSQL = "Select Customer_Guid, Customername, Fdd_Customerid From Customer Where Customerid = ? Or Customerid2 = ? Order By Modifieddate Desc Limit 1";
                    List<Map<String, Object>> checkList = jt.queryForList(checkSQL, customerId, customerId);
                    log.debug("Fix-查询系统Customer表是否存在CustomerID对应客户信息:" + checkList.size());

                    if (checkList.size() > 0) {
                        String customer_Guid = KHUtil.GetMapV(checkList.get(0), "Customer_Guid");
                        res_Json = iAPIResult.SUCCESS("", checkList);
                        res_Json.put("customer_guid", customer_Guid);
                        res_Json.put("fdd_auth_state", res_Code); // res_Code=0 等待认证 res_Code=1检查通过(已注册&已认证)
                        res_Json.put("fdd_auth_desc", "res_Code=0 等待认证 res_Code=1检查通过(已注册&已认证)");

                    } else {
                        res_Json = iAPIResult.ERROR("调用一体化&FDD处理后未检测到客户信息", res_RegJson);

                    }

                } else {
                    res_Json = iAPIResult.ERROR("检查处理导入的客户编号(注册->认证)-返回错误(" + res_Msg + ")", res_RegJson);
                }

            }

        } catch (Exception e) {
            res_Json.put("code", -1);
            res_Json.put("message", "HTTP请求调用错误，接口处理异常：" + e.getMessage());
            log.error(res_Json, e);

        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "客户资料-单客户获取一体化+法大大注册认证信息", "GetCustomerInfo", callPram, res_Json.toString(), (System.currentTimeMillis() - startTime).toString(), getMethod + ":" + mapParam.toString());
        }

        log.debug("客户资料-单客户获取一体化+法大大注册认证信息 执行结果：" + res_Json.toString());
        return res_Json.toString();
    }

}